#include <stdio.h>
#include <stdlib.h>
#include "hrd_loader.h"
#include "hrd_logger.h"
#include "hrd_problem_loader.h"
#include "hrd_object_list_loader.h"

#define BUFFER_SIZE (1024 * 1024 * 2)

static cJSON *readJsonFile(char *json_filename)
{
    FILE *fp = NULL;
    char *buffer = NULL;
    cJSON *base_json = NULL;

    buffer = calloc(sizeof(char), BUFFER_SIZE);
    if (buffer == NULL) {
        LOG_FATAL("Unable to obtain memory for buffer.");
        return NULL;
    }

    fp = fopen(json_filename, "r");
    if (fp == NULL) {
        LOG_FATAL("Fail to open file %s", json_filename);
        free(buffer);
        return NULL;
    }

    fread(buffer, sizeof(char), BUFFER_SIZE, fp);
    fclose(fp);

    base_json = cJSON_Parse(buffer);
    free(buffer);

    return base_json;
}


hrd_problem_t *HrdLoader_LoadProblem(char *json_filename, hrd_problem_t *problem)
{
    cJSON *base_json = NULL;

    base_json = readJsonFile(json_filename);
    if (base_json == NULL) {
        LOG_FATAL("Unable to parse string in file %s", json_filename);
        return NULL;
    }

    if (HrdProblemLoader_Load(base_json, problem) == NULL ||
        HrdObjectListLoader_Load(base_json, problem) == NULL)
    {
        cJSON_Delete(base_json);
        LOG_FATAL("Problem not loaded.");
        return NULL;
    }

    cJSON_Delete(base_json);

    return problem;
}